#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmc,xbmcaddon,HTMLParser
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulSoup
from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP
from tools import *
h = HTMLParser.HTMLParser()


versao = '0.2.4'
addon_id = 'plugin.video.worldiptv'
selfAddon = xbmcaddon.Addon(id=addon_id)
addonfolder = selfAddon.getAddonInfo('path')
artfolder = addonfolder + '/resources/img/'
fanart = addonfolder + '/fanart.jpg'
username = urllib.quote(selfAddon.getSetting('username'))
password = selfAddon.getSetting('password')
xml = ''


################################################## 

#MENUS############################################
def abrir_cookie(url):
        import mechanize
        import cookielib

        br = mechanize.Browser()
        cj = cookielib.LWPCookieJar()
        br.set_cookiejar(cj)
        br.set_handle_equiv(True)
        br.set_handle_gzip(True)
        br.set_handle_redirect(True)
        br.set_handle_referer(True)
        br.set_handle_robots(False)
        br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
        br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
        br.open('http://192.241.161.223:8000/admin/')
        br.select_form(nr=0)
        br.form['password']=password
        br.form['username']=username
        br.submit()
        br.open(url)
        return br.response().read()


def servers():
	global xml
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	addDir('Server 1',' ',101,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	addDir('Server 2',' ',102,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	#addDir('Server 3',' ',103,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	#addDir('Server 4',' ',104,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	addDir('Server 3 (Br)',' ',105,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	addDir('Server 4 (Br)',' ',106,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	addDir("Server 5 (Pt)"," ",2000,"http://hyperwave.com/e/GlobalRepository/Icon-Server.png")
	addDir("Server 6 (Fr)"," ",3000,"http://hyperwave.com/e/GlobalRepository/Icon-Server.png")
	addDir("Server 7 (Pt)"," ",4000,"http://hyperwave.com/e/GlobalRepository/Icon-Server.png")
	addDir("Server 8 (//)","https://www.dropbox.com/s/im25nqzwf7lz6wt/categorias.xml?dl=1",5000,"http://hyperwave.com/e/GlobalRepository/Icon-Server.png")
	addDir('Server 9',' ',107,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	addDir('Server 10',' ',108,'http://hyperwave.com/e/GlobalRepository/Icon-Server.png')
	xbmc.executebuiltin("Container.SetViewMode(500)")

def getSoup(url):
        data = abrir_cookie(url).decode('utf8')
        return BeautifulSOAP(data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)

def canais_master():
    canais = getSoup('https://www.dropbox.com/s/ju2tycbdzwviviy/NovaLista.xml?dl=1')
    for canal in canais('item'):
	addLink(canal.title.text,canal.link.text,canal.thumbnail.text)
    xbmc.executebuiltin("Container.SetViewMode(500)")

def tugas():
    canais = getSoup('https://www.dropbox.com/s/kvrf1o4c0g2lkz5/tugas.xml?dl=1')
    for canal in canais('item'):
	addLink(canal.title.text,canal.link.text,canal.thumbnail.text)
    xbmc.executebuiltin("Container.SetViewMode(500)")

def play_playtvfr(url):
    m3u8 = abrir_cookie('http://192.241.161.223:8000/canais/playtvfr?action=2&ch=%s' % url)
    xbmcPlayer = xbmc.Player()
    xbmcPlayer.play(m3u8+'|User-agent=')


def canais_tvzune():
    canais = eval(abrir_cookie('http://192.241.161.223:8000/canais/tvzune?action=1'))
    for canal in canais:
	addDir(canal[0],canal[1],'2001',canal[2],False)
    xbmc.executebuiltin("Container.SetViewMode(500)")

def play_tvzune(url):
    m3u8 = abrir_cookie('http://192.241.161.223:8000/canais/tvzune?action=2&ch=%s' % url)
    xbmcPlayer = xbmc.Player()
    xbmcPlayer.play(m3u8+'|User-agent=')



def categorias1():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[0]['baseurl']
	addDir('USA',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=3|1',2,'http://www.lyngsat-logo.com/logo/flag/az/us.png')
	addDir('Portugal',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=4|1',2,'http://www.lyngsat-logo.com/hires/flag/pt.png')
	addDir('Indian',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=1|1',2,'http://www.lyngsat-logo.com/logo/flag/az/in.png')
	addDir('Polish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=2|1',2,'http://www.lyngsat-logo.com/logo/flag/az/pl.png')
        addDir('Spanish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=5|1',2,'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRWJqAS7Z81-77-wIMjoNKQs6rA3iqfocODH6yjGpnk9CUzGXpq')
        addDir('Arabic',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=6|1',2,'http://www.lyngsat-logo.com/logo/flag/az/ae.png')
        addDir('Sports',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=7|1',2, 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSS3WWkm_wmSjZIy-zDzYBFR784L3Jl_Xr_qgTwJhcqBrGUyknCMg')
        addDir('Italia',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=8|1',2,'http://www.lyngsat-logo.com/logo/flag/az/it.png')
        addDir('France',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=9|1',2,'http://www.lyngsat-logo.com/logo/flag/az/fr.png')


def categorias2():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[1]['baseurl']
	addDir('U.K',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=2|1',12,'http://www.lyngsat-logo.com/logo/flag/az/uk.png')
	addDir('ITALY',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=5|1',12,'http://www.lyngsat-logo.com/logo/flag/az/it.png')
	addDir('BULGARIA',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=3|1',12,'http://www.lyngsat-logo.com/logo/flag/az/ru.png')
	addDir('Germany',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=7|1',12,'http://www.lyngsat-logo.com/hires/flag/de.png')
	addDir('Dinamarca',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=8|1',12,'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9c/Flag_of_Denmark.svg/370px-Flag_of_Denmark.svg.png')
	addDir('Eslovenia',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=1|1',12,'http://www.lyngsat-logo.com/logo/flag/az/sk.png')
	addDir('XXX',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=10|1',12,'http://www.samsunghdwallpaper.com/images/2014/1/1/Playboy%20logo%20141118.jpg')
        addDir('Noruega',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=11|1',12,'http://www.lyngsat-logo.com/logo/flag/az/no.png')
	addDir('Spain',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=4|1',12,'http://www.lyngsat-logo.com/logo/flag/az/es.png')
	addDir('WORLD SPORTS',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=20|1',12,'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSS3WWkm_wmSjZIy-zDzYBFR784L3Jl_Xr_qgTwJhcqBrGUyknCMg')
	#addDir('U.K',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=26|1',12,'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSS3WWkm_wmSjZIy-zDzYBFR784L3Jl_Xr_qgTwJhcqBrGUyknCMg')
	#addDir('Categoria 16',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=16|1',12,'http://www.lyngsat-logo.com/hires/flag/pt.png')

	
def categorias3():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[3]['baseurl']
	addDir('All Channels',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=*|1',13,'-')
	#addDir('Polish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=5|1',13,'http://www.lyngsat-logo.com/hires/flag/pl.png')
	addDir('Sports',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=6|1',13,'-')
	#addDir('Germany',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=7|1',13,'http://www.lyngsat-logo.com/hires/flag/de.png')
	#addDir('Dinamarca',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=8|1',13,'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9c/Flag_of_Denmark.svg/370px-Flag_of_Denmark.svg.png')
	#addDir('Eslovenia',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=9|1',13,'http://www.lyngsat-logo.com/logo/flag/az/sk.png')
	#addDir('Categoria 10',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=10|1',13,'http://www.lyngsat-logo.com/hires/flag/pt.png')
        #addDir('Noruega',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=11|1',13,'http://www.lyngsat-logo.com/logo/flag/az/no.png')
	#addDir('Spain',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=12|1',13,'http://www.lyngsat-logo.com/logo/flag/az/es.png')
	#addDir('Italy',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=13|1',13,'http://www.lyngsat-logo.com/logo/flag/az/it.png')
	#addDir('U.K',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=14|1',13,'http://www.lyngsat-logo.com/logo/flag/az/uk.png')
	#addDir('Categoria 16',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=16|1',13,'http://www.lyngsat-logo.com/hires/flag/pt.png')

def categorias4():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[4]['baseurl']
	addDir('All Channels',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=*|1',14,'-')
	addDir('Documentaries',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=5|1',14,'-')
	addDir('Sports',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=6|1',14,'-')
	addDir('Music',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=7|1',14,'-')
	addDir('Kids',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=3|1',14,'-')
	addDir('Cinema',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=4|1',14,'-')
	addDir('Adults',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=10|1',14,'http://www.lyngsat-logo.com/hires/flag/pt.png')
        addDir('International',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=11|1',14,'-')
	#addDir('Spain',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=15|1',14,'http://www.lyngsat-logo.com/logo/flag/az/es.png')
	#addDir('Italy',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=13|1',14,'http://www.lyngsat-logo.com/logo/flag/az/it.png')
	#addDir('U.K',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=14|1',14,'http://www.lyngsat-logo.com/logo/flag/az/uk.png')
	#addDir('Categoria 16',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=16|1',14,'http://www.lyngsat-logo.com/hires/flag/pt.png')


def categorias6():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[6]['baseurl']
	addDir('USA',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=3|1',15,'http://www.lyngsat-logo.com/logo/flag/az/us.png')
	addDir('Portugal',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=4|1',15,'http://www.lyngsat-logo.com/hires/flag/pt.png')
	addDir('Indian',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=1|1',15,'http://www.lyngsat-logo.com/logo/flag/az/in.png')
	addDir('Polish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=2|1',15,'http://www.lyngsat-logo.com/logo/flag/az/pl.png')
        addDir('Spanish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=5|1',15,'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRWJqAS7Z81-77-wIMjoNKQs6rA3iqfocODH6yjGpnk9CUzGXpq')
        addDir('Arabic',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=6|1',15,'http://www.lyngsat-logo.com/logo/flag/az/ae.png')
        addDir('Sports',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=7|1',15, 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSS3WWkm_wmSjZIy-zDzYBFR784L3Jl_Xr_qgTwJhcqBrGUyknCMg')
        addDir('Italia',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=8|1',15,'http://www.lyngsat-logo.com/logo/flag/az/it.png')
        addDir('France',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=9|1',15,'http://www.lyngsat-logo.com/logo/flag/az/fr.png')


def play_canal6(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[6]['baseurl']
	mac = soup('token')[6]['mac']
	barer = soup('token')[6]['barer']
        url = baseurl + '/stalker_portal/server/load.php?type=itv&action=create_link&cmd=ffmpeg+http://localhost/ch/%s&series=&forced_storage=undefined&disable_ad=0&JsHttpRequest=1-xml' % url
        import urllib
        #url = urllib.quote_plus(url)
        print url
        import json
	codigo_fonte = abrir_url_stalker6(url)
	print codigo_fonte
        rjson = json.loads(codigo_fonte)
        print rjson
        stream = rjson['js']['cmd'].replace('ffmpeg ','').replace('ffrt3 ', '')
        print stream
        xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	xbmcPlayer.play(stream+'|User-agent=Lavf53.32.100')

def listar_canais6(url):
        import json
        pagina = url.split('|')[1]
        url = url.split('|')[0]
	codigo_fonte = abrir_url_stalker6(url + '&fav=0&sortby=number&hd=0&p=%s&JsHttpRequest=1-xml' % pagina)
        rjson = json.loads(codigo_fonte)
        canais =  rjson['js']['data']
        for canal in canais:
                id_ = canal['cmds'][0]['id']
                nome = canal['name']
                print nome
                addDir(nome,id_,66,'',False,len(canais),'')
        ppagina = int(pagina) + 1
        if not len(canais) < 14:
                addDir('Proxima Pagina >>',url + '|' + str(ppagina),15,artfolder + '')

def abrir_url_stalker6(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[6]['baseurl']
	mac = soup('token')[6]['mac']
	barer = soup('token')[6]['barer']
        import urllib2
        opener = urllib2.build_opener()
        opener.addheaders.append(('Authorization', 'Bearer ' + barer))
        opener.addheaders.append(('Cookie', 'mac=' + mac + '; stb_lang=en; timezone=America%2FToronto'))
        opener.addheaders.append(('X-User-Agent', 'Model: MAG250; Link: WiFi'))
        opener.addheaders.append(('User-Agent', 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 4 rev: 1209 Mobile Safari/533.3'))
        opener.addheaders.append(('Host', '50.7.74.98:88'))
        opener.addheaders.append(('Referer', baseurl + '/stalker_portal/c/'))
        f = opener.open(url)
        return f.read()

#server 7

def categorias7():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[8]['baseurl']
	addDir('USA',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=3|1',18,'http://www.lyngsat-logo.com/logo/flag/az/us.png')
	addDir('Portugal',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=4|1',18,'http://www.lyngsat-logo.com/hires/flag/pt.png')
	addDir('Indian',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=1|1',18,'http://www.lyngsat-logo.com/logo/flag/az/in.png')
	addDir('Polish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=2|1',18,'http://www.lyngsat-logo.com/logo/flag/az/pl.png')
        addDir('Spanish',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=5|1',18,'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRWJqAS7Z81-77-wIMjoNKQs6rA3iqfocODH6yjGpnk9CUzGXpq')
        addDir('Arabic',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=6|1',18,'http://www.lyngsat-logo.com/logo/flag/az/ae.png')
        addDir('Sports',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=7|1',18, 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSS3WWkm_wmSjZIy-zDzYBFR784L3Jl_Xr_qgTwJhcqBrGUyknCMg')
        addDir('Italia',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=8|1',18,'http://www.lyngsat-logo.com/logo/flag/az/it.png')
        addDir('France',baseurl + '/stalker_portal/server/load.php?type=itv&action=get_ordered_list&genre=9|1',18,'http://www.lyngsat-logo.com/logo/flag/az/fr.png')


def play_canal7(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	#print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[8]['baseurl']
	mac = soup('token')[8]['mac']
	barer = soup('token')[8]['barer']
        url = baseurl + '/stalker_portal/server/load.php?type=itv&action=create_link&cmd=ffmpeg+http://localhost/ch/%s&series=&forced_storage=undefined&disable_ad=0&JsHttpRequest=1-xml' % url
        import urllib
        #url = urllib.quote_plus(url)
        print url
        import json
	codigo_fonte = abrir_url_stalker7(url)
	print codigo_fonte
        rjson = json.loads(codigo_fonte)
        print rjson
        stream = rjson['js']['cmd'].replace('ffmpeg ','').replace('ffrt3 ', '')
        print stream
        xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	xbmcPlayer.play(stream+'|User-agent=Lavf53.32.100')

def listar_canais7(url):
        import json
        pagina = url.split('|')[1]
        url = url.split('|')[0]
	codigo_fonte = abrir_url_stalker7(url + '&fav=0&sortby=number&hd=0&p=%s&JsHttpRequest=1-xml' % pagina)
        rjson = json.loads(codigo_fonte)
        canais =  rjson['js']['data']
        for canal in canais:
                id_ = canal['cmds'][0]['id']
                nome = canal['name']
                print nome
                addDir(nome,id_,77,'',False,len(canais),'')
        ppagina = int(pagina) + 1
        if not len(canais) < 14:
                addDir('Proxima Pagina >>',url + '|' + str(ppagina),18,artfolder + '')

def abrir_url_stalker7(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[8]['baseurl']
	mac = soup('token')[8]['mac']
	barer = soup('token')[8]['barer']
        import urllib2
        opener = urllib2.build_opener()
        opener.addheaders.append(('Authorization', 'Bearer ' + barer))
        opener.addheaders.append(('Cookie', 'mac=' + mac + '; stb_lang=en; timezone=America%2FToronto'))
        opener.addheaders.append(('X-User-Agent', 'Model: MAG250; Link: WiFi'))
        opener.addheaders.append(('User-Agent', 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 4 rev: 1209 Mobile Safari/533.3'))
        opener.addheaders.append(('Host', '50.7.74.98:88'))
        opener.addheaders.append(('Referer', baseurl + '/stalker_portal/c/'))
        f = opener.open(url)
        return f.read()







def abrir_url_stalker4(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[4]['baseurl']
	mac = soup('token')[4]['mac']
	barer = soup('token')[4]['barer']
        import urllib2
        opener = urllib2.build_opener()
        opener.addheaders.append(('Authorization', 'Bearer ' + barer))
        opener.addheaders.append(('Cookie', 'mac=' + mac + '; stb_lang=en; timezone=America%2FToronto'))
        opener.addheaders.append(('X-User-Agent', 'Model: MAG250; Link: WiFi'))
        opener.addheaders.append(('User-Agent', 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 4 rev: 1209 Mobile Safari/533.3'))
        opener.addheaders.append(('Host', '195.170.166.18'))
        opener.addheaders.append(('Referer', baseurl + '/stalker_portal/c/index.html'))
        f = opener.open(url)
        return f.read()


def abrir_url_stalker3(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[3]['baseurl']
	mac = soup('token')[3]['mac']
	barer = soup('token')[3]['barer']
        import urllib2
        opener = urllib2.build_opener()
        opener.addheaders.append(('Authorization', 'Bearer ' + barer))
        opener.addheaders.append(('Cookie', 'mac=' + mac + '; stb_lang=en; timezone=America%2FToronto'))
        opener.addheaders.append(('X-User-Agent', 'Model: MAG250; Link: WiFi'))
        opener.addheaders.append(('User-Agent', 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 4 rev: 1209 Mobile Safari/533.3'))
        opener.addheaders.append(('Host', '195.170.166.18'))
        opener.addheaders.append(('Referer', baseurl + '/stalker_portal/c/index.html'))
        f = opener.open(url)
        return f.read()

def abrir_url_stalker2(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[1]['baseurl']
	mac = soup('token')[1]['mac']
	barer = soup('token')[1]['barer']
        import urllib2
        opener = urllib2.build_opener()
        opener.addheaders.append(('Authorization', 'Bearer ' + barer))
        opener.addheaders.append(('Cookie', 'mac=' + mac + '; stb_lang=en; timezone=America%2FToronto'))
        opener.addheaders.append(('X-User-Agent', 'Model: MAG250; Link: WiFi'))
        opener.addheaders.append(('User-Agent', 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 4 rev: 1209 Mobile Safari/533.3'))
        opener.addheaders.append(('Host', '195.170.166.18'))
        opener.addheaders.append(('Referer', baseurl + '/stalker_portal/c/index.html'))
        f = opener.open(url)
        return f.read()

def abrir_url_stalker(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[0]['baseurl']
	mac = soup('token')[0]['mac']
	barer = soup('token')[0]['barer']
        import urllib2
        opener = urllib2.build_opener()
        opener.addheaders.append(('Authorization', 'Bearer ' + barer))
        opener.addheaders.append(('Cookie', 'mac=' + mac + '; stb_lang=en; timezone=America%2FToronto'))
        opener.addheaders.append(('X-User-Agent', 'Model: MAG250; Link: WiFi'))
        opener.addheaders.append(('User-Agent', 'Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) MAG200 stbapp ver: 4 rev: 1209 Mobile Safari/533.3'))
        opener.addheaders.append(('Host', '50.7.74.98:88'))
        opener.addheaders.append(('Referer', baseurl + '/stalker_portal/c/'))
        f = opener.open(url)
        return f.read()

def server6():
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	for canal in soup('item'):
		addLink(canal.title.text,canal.link.text,canal.thumbnail.text)

def listar_canais(url):
        import json
        pagina = url.split('|')[1]
        url = url.split('|')[0]
	codigo_fonte = abrir_url_stalker(url + '&fav=0&sortby=number&hd=0&p=%s&JsHttpRequest=1-xml' % pagina)
        rjson = json.loads(codigo_fonte)
        canais =  rjson['js']['data']
        for canal in canais:
                id_ = canal['cmds'][0]['id']
                nome = canal['name']
                print nome
                addDir(nome,id_,6,'',False,len(canais),'')
        ppagina = int(pagina) + 1
        if not len(canais) < 14:
                addDir('Proxima Pagina >>',url + '|' + str(ppagina),2,artfolder + '')

def listar_canais2(url):
        import json
        pagina = url.split('|')[1]
        url = url.split('|')[0]
	codigo_fonte = abrir_url_stalker2(url + '&fav=0&sortby=number&hd=0&p=%s&JsHttpRequest=1-xml&from_ch_id=0' % pagina)
        rjson = json.loads(codigo_fonte)
        canais =  rjson['js']['data']
        for canal in canais:
                id_ = canal['cmds'][0]['id']
                urlc = canal['cmd'].replace('ffmpeg ','').replace('ffrt3 ', '') + '|User-agent=Lavf53.32.100'
                nome = canal['name']
                print nome
                addLink(nome,urlc,'')
        ppagina = int(pagina) + 1
        if not len(canais) < 14:
                addDir('Proxima Pagina >>',url + '|' + str(ppagina),12,artfolder + '')

def listar_canais3(url):
        import json
        pagina = url.split('|')[1]
        url = url.split('|')[0]
	codigo_fonte = abrir_url_stalker3(url + '&fav=0&sortby=number&hd=0&p=%s&JsHttpRequest=1-xml&from_ch_id=0' % pagina)
	print codigo_fonte
        rjson = json.loads(codigo_fonte)
        canais =  rjson['js']['data']
	print canais
        for canal in canais:
		print canal
                id_ = canal['cmds'][0]['id']
		print canal['cmds'][0]['url']
                urlc = canal['cmds'][0]['url'].replace('ffrt2 ','').replace('ffrt','') + ''
                nome = canal['name']
                addDir(nome,urlc,66,'',False,len(canais),'')
        ppagina = int(pagina) + 1
        if not len(canais) < 14:
                addDir('Proxima Pagina >>',url + '|' + str(ppagina),13,artfolder + '')

def listar_canais4(url):
        import json
        pagina = url.split('|')[1]
        url = url.split('|')[0]
	codigo_fonte = abrir_url_stalker4(url + '&fav=0&sortby=number&hd=0&p=%s&JsHttpRequest=1-xml&from_ch_id=0' % pagina)
	print codigo_fonte
        rjson = json.loads(codigo_fonte)
        canais =  rjson['js']['data']
	print canais
        for canal in canais:
		print canal
                id_ = canal['cmds'][0]['id']
		print canal['cmds'][0]['url']
                urlc = canal['cmds'][0]['url'].replace('ffrt2 ','').replace('ffrt','') + ''
                nome = canal['name']
                addDir(nome,urlc,66,'',False,len(canais),'')
        ppagina = int(pagina) + 1
        if not len(canais) < 14:
                addDir('Proxima Pagina >>',url + '|' + str(ppagina),14,artfolder + '')

def listar_categorias_xml():
    xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
    soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
    categorias = soup('categoria')
    for categoria in categorias:
	addDir(categoria.nome.text,categoria.link.text,5002,categoria.logo.text)
    xbmc.executebuiltin("Container.SetViewMode(500)")

def listar_canais_xml(url):
    canais = getSoup(url)
    for canal in canais('item'):
	addLink(canal.title.text,canal.link.text,canal.thumbnail.text)
    xbmc.executebuiltin("Container.SetViewMode(500)")


def play1(url):
	xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	xbmcPlayer.play(url)

def play_canal(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[0]['baseurl']
	mac = soup('token')[0]['mac']
	barer = soup('token')[0]['barer']
        url = baseurl + '/stalker_portal/server/load.php?type=itv&action=create_link&cmd=ffrt+http://localhost/ch/%s&series=&forced_storage=undefined&disable_ad=0&JsHttpRequest=1-xml' % url
        import urllib
        #url = urllib.quote_plus(url)
        print url
        import json
	codigo_fonte = abrir_url_stalker(url)
        rjson = json.loads(codigo_fonte)
        print rjson
        stream = rjson['js']['cmd'].replace('ffmpeg ','').replace('ffrt3 ', '')
        opener = urllib2.build_opener(urllib2.HTTPRedirectHandler)
	request = opener.open(stream)
	stream = request.url
        print stream
        xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	xbmcPlayer.play(stream)

def play_canal2(url):
	xml = abrir_cookie('http://192.241.161.223:8000/canais/tokens/')
	print xml
	soup = BeautifulSOAP(xml, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
	baseurl = soup('token')[1]['baseurl']
	mac = soup('token')[1]['mac']
	barer = soup('token')[1]['barer']
        url = baseurl + '/stalker_portal/server/load.php?type=itv&action=create_link&cmd=ffrt+http://localhost/ch/%s&series=&forced_storage=undefined&disable_ad=0&JsHttpRequest=1-xml' % url
        import urllib
        #url = urllib.quote_plus(url)
        print url
        import json
	codigo_fonte = abrir_url_stalker(url)
	print codigo_fonte
        rjson = json.loads(codigo_fonte)
        print rjson
        stream = rjson['js']['cmd'].replace('ffmpeg ','')
        print stream
        xbmcPlayer = xbmc.Player(xbmc.PLAYER_CORE_AUTO)
	xbmcPlayer.play(stream)

def abrir_url(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link

def addLink(name,url,iconimage):
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
	return ok

#def addDir(name,url,mode,iconimage,pasta=True,total=1):
#	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
#	ok=True
#	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
#	liz.setProperty('fanart_image', fanart)
#	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=total)
#	return ok

def addDir(name,url,mode,iconimage,pasta=True,total=1,plot=''):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setProperty('fanart_image', fanart)
	liz.setInfo( type="video", infoLabels={ "title": name, "plot": plot } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=total)
	return ok

############################################################################################################
#                                               GET PARAMS                                                 #
############################################################################################################
              
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

      
params=get_params()
url=None
name=None
mode=None
iconimage=None


try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

try:        
        iconimage=urllib.unquote_plus(params["iconimage"])
except:
        pass


print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)
print "Iconimage: "+str(iconimage)




###############################################################################################################
#                                                   MODOS                                                     #
###############################################################################################################


if mode==None or url==None or len(url)<1:
        print ""
        servers()

elif mode==101:
	print ""
	categorias1()
elif mode==102:
	print ""
	categorias2()
elif mode==103:
	print ""
	categorias3()
elif mode==104:
	print ""
	categorias4()
elif mode==105:
	canais_master()
elif mode==106:
	server6()
elif mode==107:
	categorias6()
elif mode==108:
	categorias7()
elif mode==2000:
	canais_tvzune()
elif mode==2001:
	play_tvzune(url)
elif mode==3000:
	canais_playtvfr()
elif mode==3001:
	play_playtvfr(url)
elif mode==4000:
        tugas()
elif mode==5000:
	listar_categorias_xml()
elif mode==5002:
	listar_canais_xml(url)
	
elif mode==2:
	print ""
	listar_canais(url)
	
elif mode==7:
	print ""
        play_canal2(url)	

elif mode==6:
	print ""
	play_canal(url)

elif mode==66:
	print ""
	play_canal6(url)

elif mode==77:
	print ""
	play_canal7(url)
	
elif mode==5:
	print ""
	listar_videos_M18(url)
elif mode==12:
        listar_canais2(url)
elif mode==13:
        listar_canais3(url)
elif mode==14:
	listar_canais4(url)
elif mode==15:
	listar_canais6(url)
elif mode==18:
	listar_canais7(url)
elif mode==66:
	play1(url)
	
xbmcplugin.endOfDirectory(int(sys.argv[1]))
